package com.honestpeak.datafusion.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honestpeak.core.datasource.DataSourceContextHolder;
import com.honestpeak.core.datasource.DataSourceType;
import com.honestpeak.core.utils.WebUtils;
import com.honestpeak.datafusion.common.Const;
import com.honestpeak.datafusion.common.ServerResponse;
import com.honestpeak.datafusion.enums.ClubMemberEnum;
import com.honestpeak.datafusion.mapper.ClubMemberDistMapper;
import com.honestpeak.datafusion.mapper.HpamsMapper;
import com.honestpeak.datafusion.model.BaseModel;
import com.honestpeak.datafusion.model.Department;
import com.honestpeak.datafusion.model.PlatformActiveCount;
import com.honestpeak.datafusion.service.PlatformService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @Auther: apple
 * @Date: 2018/8/22 18:08
 * @Description:
 */
@Service
@Slf4j

public class PlatformServiceImpl implements PlatformService {

    @Autowired
    private HpamsMapper hpamsMapper;

    @Autowired
    private ClubMemberDistMapper clubMemberDistMapper;

    /**
     * 今日活动人数
     * @return
     */
    @Override
    public List<Map<String, Object>> getTodayActiveCount() {
        String day = WebUtils.DateToString(new Date());
        List<Map<String, Object>> resultMapList = Lists.newArrayList();
        //俱乐部Map
        Map<String, Object> clubResultMap = Maps.newHashMap();
        //组装晨跑的Map
        Map<String, Object> cpResultMap = Maps.newHashMap();
        //健步Map
        Map<String, Object> jbResultMap = Maps.newHashMap();
        //TODO 俱乐部 模拟
        clubResultMap.put("name", "俱乐部");
        clubResultMap.put("value", 0);

        //晨跑
        DataSourceContextHolder.setDbType(DataSourceType.HPAMS);
        PlatformActiveCount cPplatformActiveCount = hpamsMapper.getTodayActiveCount(day);
        cpResultMap.put("name", cPplatformActiveCount.getName());
        cpResultMap.put("value", cPplatformActiveCount.getValue());
        DataSourceContextHolder.clearDbType();

        //TODO 健步 模拟
        jbResultMap.put("name", "健步");
        jbResultMap.put("value", 0);

        resultMapList.add(clubResultMap);
        resultMapList.add(cpResultMap);
        resultMapList.add(jbResultMap);
        return resultMapList;
    }

    /**
     * 俱乐部今日活动人数
     * @return
     */
    @Override
    public List<Map<String, Object>> getTodayClubActiveCount() {
        String day = WebUtils.DateToString(new Date());
        List<Map<String, Object>> resultMapList = Lists.newArrayList();

        //切换数据源
        DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
        //初级会员
        Map<String, Object> juniorMap = Maps.newHashMap();
        PlatformActiveCount juniorPlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_JUNIOR.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_JUNIOR.getCode(),0));
        juniorMap.put("name", "初级会员");
        juniorMap.put("value", juniorPlatformActiveCount.getValue());
        //中级会员
        Map<String, Object> intermediateMap = Maps.newHashMap();
        PlatformActiveCount intermediatePlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_INTERMEDIATE.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_INTERMEDIATE.getCode(),0));
        intermediateMap.put("name", "中级会员");
        intermediateMap.put("value", intermediatePlatformActiveCount.getValue());
        //高级会员
        Map<String ,Object> seniorMap =Maps.newHashMap();
        PlatformActiveCount seniorPlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_SENIOR.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_SENIOR.getCode(),0));
        seniorMap.put("name", "高级会员");
        seniorMap.put("value", seniorPlatformActiveCount.getValue());
        DataSourceContextHolder.clearDbType();
        resultMapList.add(juniorMap);
        resultMapList.add(intermediateMap);
        resultMapList.add(seniorMap);
        return resultMapList;
    }

    /**
     * 俱乐部当日活跃排行榜
     * @return
     */
    @Override
    public List<Map<String, Object>> getTodayClubActiveRanking() {
//        String day = WebUtils.DateToString(new Date());
        String day = "2017-09-23";
        DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
        List<Map<String, Object>> platformActiveCountMapList = Lists.newArrayList();
        //俱乐部查询 id：俱乐部id, name 俱乐部名称, value：俱乐部实际人数
        List<PlatformActiveCount> clubListList = hpamsMapper.getActualNumberOClubsByDay();
        clubListList.stream().forEach(x -> {

            Map<String, Object> map = Maps.newHashMap();
            //俱乐部人数
            int totalCount = x.getValue();

            //准会员
            PlatformActiveCount associateMemberPlatformActiveCount = Optional.ofNullable(hpamsMapper.getAssociateMember(day, x.getId())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_ASSOCIATE.getCode(), 0));
            int AassociateClubPeopleTotalCount = associateMemberPlatformActiveCount.getValue();
            //初级会员
            PlatformActiveCount juniorPlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_JUNIOR.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_JUNIOR.getCode(),0));
            int juniorClubPeopleTotalCount = juniorPlatformActiveCount.getValue();
            //中级会员
            PlatformActiveCount intermediatePlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_INTERMEDIATE.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_INTERMEDIATE.getCode(), 0));
            int intermediateClubPeopleTotalCount = intermediatePlatformActiveCount.getValue();
            //高级会员
            PlatformActiveCount seniorPlatformActiveCount = Optional.ofNullable(hpamsMapper.getClubMemberCount(day, ClubMemberEnum.CLUB_MEMBER_SENIOR.getCode())).orElse(new PlatformActiveCount(ClubMemberEnum.CLUB_MEMBER_SENIOR.getCode(), 0));
            int seniorClubPeopleTotalCount = seniorPlatformActiveCount.getValue();
            //俱乐部签到人数
            int clubPeopleTotalCount = AassociateClubPeopleTotalCount + juniorClubPeopleTotalCount + intermediateClubPeopleTotalCount + seniorClubPeopleTotalCount;
            //签到人数占比 保留两位
            double ratioAccount = clubPeopleTotalCount / totalCount;
            ratioAccount = new BigDecimal(ratioAccount).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("id" ,x.getId());
            map.put("name" , x.getName());
            map.put("value" ,ratioAccount);
            platformActiveCountMapList.add(map);
        });
        // 排序代码如下
        List<Map<String, Object>> result = platformActiveCountMapList.stream().sorted(Comparator.comparing(PlatformServiceImpl::comparingByValue).reversed()).collect(Collectors.toList());

        DataSourceContextHolder.clearDbType();
        return result.stream().limit(Const.DEFAULT_DISPLAY_QUANTITY).collect(Collectors.toList());
    }

    /**
     * 数据比较，各系活动人数,俱乐部。晨跑，健步
     * @param departList
     * @return
     */
    @Override
    public ServerResponse<Object> getDataComparisons(List<String> departList, String year) {
        StringBuilder yearBuilder = new StringBuilder();
        if(StringUtils.isEmpty(year)){
            yearBuilder.append(WebUtils.DateToString(new Date()));
        }
        List<String> departNameList = Lists.newArrayList();
        if(CollectionUtils.isEmpty(departList)){
            //获取俱乐部院系
            DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
            List<String> clubDepartList = clubMemberDistMapper.getAllDepartmentNameList();
            DataSourceContextHolder.clearDbType();
            //获取晨跑中的院系
            DataSourceContextHolder.setDbType(DataSourceType.HPAMS);
            List<String> hpamsDepartList = hpamsMapper.getAllDepartmentNameList();
            DataSourceContextHolder.clearDbType();
            clubDepartList.stream().forEach(club -> departNameList.add(club));
            hpamsDepartList.stream().forEach(hpams -> departNameList.add(hpams));
            log.info("departNameList:{}" ,departNameList);
            departList = departNameList.stream().distinct().collect(Collectors.toList());
        }
        List<Map<String, Object>> resultMapList = Lists.newArrayList();
        //俱乐部
        Map<String, Object> clubResultMap = Maps.newHashMap();
        Map<String, Object> hpamsResultMap = Maps.newHashMap();
        List<Map<String, Object>> clubMapList = Lists.newArrayList();
        List<Map<String, Object>> hpamsMapList = Lists.newArrayList();
        departList.stream().forEach(x -> {
            DataSourceContextHolder.setDbType(DataSourceType.SPORTS);
            Map<String, Object> clubMap = Maps.newHashMap();
            BaseModel clubBaseModel = Optional.ofNullable(clubMemberDistMapper.getDepartActiveCount(x, yearBuilder.toString())).orElse(new BaseModel(0));
            clubMap.put("name" , x);
            clubMap.put("value" , clubBaseModel.getValue());
            clubMapList.add(clubMap);
            DataSourceContextHolder.clearDbType();

            //晨跑
            DataSourceContextHolder.setDbType(DataSourceType.HPAMS);
            Map<String, Object> hpamsMap = Maps.newHashMap();
            BaseModel hpamsBaseModel = Optional.ofNullable(hpamsMapper.getDepartActiveCount(x ,yearBuilder.toString())).orElse(new BaseModel(0));
            hpamsMap.put("name", x);
            hpamsMap.put("value", hpamsBaseModel.getValue());
            hpamsMapList.add(hpamsMap);
            DataSourceContextHolder.clearDbType();

            //TODO 健步
        });
        clubResultMap.put("name","俱乐部");
        clubResultMap.put("items", clubMapList);
        hpamsResultMap.put("name", "晨跑");
        hpamsResultMap.put("items", hpamsMapList);
        resultMapList.add(clubResultMap);
        resultMapList.add(hpamsResultMap);

        return ServerResponse.createBySuccess(resultMapList);
    }

    /**
     * 根据Map中的value排序，Map必须含有key -> key 是 value
     * @param map
     * @return
     */
    private static Double comparingByValue(Map<String, Object> map){
        return (Double) map.get("value");
    }



}
